﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Controls;
using TestMySqlConnetPoll;
using System.Threading;
using DevExpress.XtraCharts;
using DevExpress.XtraBars;
using System.Drawing.Imaging;

namespace View.Chart.DC
{
    public enum DCDZCurveTYPE
    {
        道岔动作电流曲线,
        道岔动作功率曲线
    }

    /// <summary>
    /// 道岔电流、功率动作曲线
    /// </summary>
    public partial class DCDZCurve : DevExpress.XtraEditors.XtraForm
    {
        private DcdlqxTable dcqx = new DcdlqxTable();
        private System.Globalization.CultureInfo cu = new System.Globalization.CultureInfo("zh-CN");

        private DCDZCurveTYPE cTYPE;

        // 当前查询到的道岔电流、功率数据    -------左侧
        ObjDcdlType now_dcdl_left = null;

        // 当前查询到的道岔摩擦电流、功率数据-------左侧
        ObjDcdlType now_dcdl_mc_left = null;

        // 当前查询到的道岔标准电流、功率数据-------左侧
        ObjDcdlType now_dcdl_bz_left = null;

        // 当前查询到的道岔电流、功率数据    -------左侧
        ObjDcdlType now_dcdl_right = null;

        // 当前查询到的道岔摩擦电流、功率数据-------左侧
        ObjDcdlType now_dcdl_mc_right = null;

        // 当前查询到的道岔标准电流、功率数据-------左侧
        ObjDcdlType now_dcdl_bz_right = null;

        DateTime dtNowSel = DateTime.MaxValue;
        DateTime dtNowSel_Next = DateTime.MaxValue;

        private DateTime sTime = DateTime.Now;

        public DCDZCurve(DCDZCurveTYPE curveType)
        {
            InitializeComponent();
            LoadDeviceList();
            repositoryItemComboBox1.SelectedIndexChanged += new EventHandler(CurveType_SelectedIndexChanged);
            this.barRadioTime.Edit.EditValueChanged += new EventHandler(RadioTimeEdit_EditValueChanged);

            //曲线类型
            this.cBoxCurveType.EditValue = curveType.ToString();
            this.Text = curveType.ToString();

            //设备名
            if (repositoryItemComboBox2.Items.Count > 0)
                this.cBoxCurveName.EditValue = (this.cBoxCurveName.Edit as RepositoryItemComboBox).Items[0];
            this.barRadioTime.EditValue = (this.barRadioTime.Edit as RepositoryItemRadioGroup).Items[0].Value;

            //时间列表
            this.cBoxCurveTime.Enabled = false;
            if (repositoryItemComboBox3.Items.Count > 0)
                this.cBoxCurveTime.EditValue = repositoryItemComboBox3.Items[0];
        }

        void repositoryItemComboBox3_EditValueChanged(object sender, EventArgs e)
        {
            dtNowSel = DateTime.Parse((string)this.cBoxCurveTime.EditValue, cu);

            if (editindex < (repositoryItemComboBox3.Items.Count - 1))
                dtNowSel_Next = DateTime.Parse((string)repositoryItemComboBox3.Items[(editindex + 1)], cu);
            else
                dtNowSel_Next = DateTime.MaxValue;

            editindex = (sender as ComboBoxEdit).SelectedIndex;

            GenCurveData();
        }

        private string PerScanName = string.Empty;

        protected override void OnClosing(CancelEventArgs e)
        {
            MySql.InsertUserScanT("道岔动作电流曲线浏览记录", this.Text, sTime, DateTime.Now, "实时值");
            base.OnClosing(e);
        }
        /// <summary>
        /// 曲线类型改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void CurveType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PerScanName != string.Empty)
                MySql.InsertUserScanT("道岔动作电流曲线浏览记录", PerScanName, sTime, DateTime.Now, "实时值");

            if ((sender as ComboBoxEdit).SelectedIndex == 0)
            {
                cTYPE = DCDZCurveTYPE.道岔动作电流曲线;
                this.Text = "道岔动作电流曲线";
            }
            else
            {
                cTYPE = DCDZCurveTYPE.道岔动作功率曲线;
                this.Text = "道岔动作功率曲线";
            }

            PerScanName = this.Text;

            if ((dcqx.DcdlqxValueList.Count > 0) && dcqx.DcdlqxValueList.ContainsKey(DateTime.Parse((string)this.cBoxCurveTime.EditValue, cu)))
            {
                //画左侧曲线
                SearchCurve(this.chart_left, true, DateTime.Parse((string)this.cBoxCurveTime.EditValue, cu));
                //return;
            }
            //画右侧曲线
            if (editindex < (repositoryItemComboBox3.Items.Count - 1))
                SearchCurve(this.chart_right, false, DateTime.Parse((string)repositoryItemComboBox3.Items[(editindex + 1)], cu));

            sTime = DateTime.Now;
        }

        /// <summary>
        /// 曲线设备选择改变,刷新时间列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CBoxCurveName_EditValueChanged(object sender, EventArgs e)
        {
            CreateTimeListForDev((string)this.cBoxCurveName.EditValue);
        }

        /// <summary>
        /// 曲线时间改变，刷新曲线数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CBoxCurveTime_EditValueChanged(object sender, EventArgs e)
        {
            dtNowSel = DateTime.Parse((string)this.cBoxCurveTime.EditValue, cu);
            //repositoryItemComboBox3.Items.IndexOf()

            if (editindex < (repositoryItemComboBox3.Items.Count - 1))
                dtNowSel_Next = DateTime.Parse((string)repositoryItemComboBox3.Items[(editindex + 1)], cu);
            else
                dtNowSel_Next = DateTime.MaxValue;

            editindex = repositoryItemComboBox3.Items.IndexOf(this.cBoxCurveTime.EditValue);

            GenCurveData();
        }

        bool isHasMC = false, isHasBZ = false;
        int editindex;
        /// <summary>
        /// 曲线时间改变,刷新曲线数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void CurveTime_SelectedIndexChanged(object sender, EventArgs e)
        {           
            dtNowSel = DateTime.Parse((string)this.cBoxCurveTime.EditValue, cu);

            if (editindex < (repositoryItemComboBox3.Items.Count - 1))
                dtNowSel_Next = DateTime.Parse((string)repositoryItemComboBox3.Items[(editindex + 1)], cu);
            else
                dtNowSel_Next = DateTime.MaxValue;

            editindex = (sender as ComboBoxEdit).SelectedIndex;

            GenCurveData();
        }

        private void GenCurveData()
        {
            //if (checkStand.Checked)
            //    isHasMC = true;
            //if (checkMC.Checked)
            //    isHasBZ = true;

            this.chart_left.Series.Clear();
            this.chart_right.Series.Clear();

            //获取当前选择时间曲线数据
            CreateSeriesPoint(DateTime.Parse((string)this.cBoxCurveTime.EditValue, cu),
                (string)this.cBoxCurveName.EditValue, this.chart_left, isHasMC, isHasBZ, true);
            SearchCurve(this.chart_left, true, DateTime.Parse((string)this.cBoxCurveTime.EditValue, cu));

            //获取相邻时间的曲线数据
            if (editindex < (repositoryItemComboBox3.Items.Count - 1))
            {
                CreateSeriesPoint(DateTime.Parse((string)repositoryItemComboBox3.Items[(editindex + 1)], cu),
                    (string)this.cBoxCurveName.EditValue, this.chart_right, isHasMC, isHasBZ, false);
                SearchCurve(this.chart_right, false, DateTime.Parse((string)repositoryItemComboBox3.Items[(editindex + 1)], cu));
            }
        }

        /// <summary>
        /// 时间选项改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void RadioTimeEdit_EditValueChanged(object sender, EventArgs e)
        {
            if (barManager1.ActiveEditor != null)
            {
                int editvalue = (int)(barManager1.ActiveEditor as RadioGroup).EditValue;
                if (editvalue == 1)
                {
                    this.cBoxCurveTime.Enabled = true;
                }
                else
                {
                    this.cBoxCurveTime.Enabled = false;
                }
            }
        }

        /// <summary>
        /// 加载设备列表
        /// </summary>
        private void LoadDeviceList()
        {
            foreach (objDcdlqxStruct dc in c_Device.DcdlqxDevList)
            {
                repositoryItemComboBox2.Items.Add(dc.DevName);
            }
        }

        private string GetOrderName(byte order)
        {
            switch (order)
            {
                case 0:
                    return "定位到反位";
                case 1:
                    return "反位到定位";
                case 2:
                    return "定位到定位";
                case 3:
                    return "反位到反位";
                case 4:
                    return "定位到故障位";
                case 5:
                    return "反位到故障位";
                case 6:
                    return "故障位到定位";
                case 7:
                    return "故障位到反位";
                case 8:
                    return "故障位到故障位";
                default:
                    return "";

            }
        }

        // 2- 3- 4- 5- 6 7- 8-
        private void SearchCurve(ChartControl chart, bool isLeft, DateTime time)
        {
            chart.Series.Clear();
            ObjDcdlType dcdl;
            if (isLeft)
                dcdl = now_dcdl_left;
            else
                dcdl = now_dcdl_right;

            if (isLeft)
                this.lbl_left.Text = "时间及动作方向:" + GetOrderName(dcdl.zh_order) + "  " + time.ToString("s", cu);
            else
                this.lbl_Right.Text = "时间及动作方向:" + GetOrderName(dcdl.zh_order) + "  " + time.ToString("s", cu);

            if (cTYPE == DCDZCurveTYPE.道岔动作电流曲线)
            {
                //A相
                CreateSeries("A相", chart, dcdl.qxA);
                //B相
                if (dcdl.qxB != null && dcdl.qxB.Count > 0)
                    CreateSeries("B相", chart, dcdl.qxB);
                //C相
                if (dcdl.qxC != null && dcdl.qxC.Count > 0)
                    CreateSeries("C相", chart, dcdl.qxC);
            }
            else if (cTYPE == DCDZCurveTYPE.道岔动作功率曲线)
            {
                CreateSeries("功率", chart, dcdl.glqx);
            }

            if (isHasMC)
            {
                CreateMCSeries(chart, isLeft);
            }

            if (isHasBZ)
            {
                CreateBZSeries(chart, isLeft);
            }
        }

        /// <summary>
        /// 生成摩擦曲线
        /// </summary>
        private void CreateMCSeries(ChartControl chart, bool isLeft)
        {
            //chart.Series.Clear();
            ObjDcdlType dcdl;
            if (isLeft)
                dcdl = now_dcdl_mc_left;
            else
                dcdl = now_dcdl_mc_right;

            if (dcdl == null)
                return;

            if (cTYPE == DCDZCurveTYPE.道岔动作电流曲线)
            {
                //A相
                CreateSeries("A相摩擦", chart, dcdl.qxA); 
                //B相
                if (dcdl.qxB != null && dcdl.qxB.Count > 0)
                    CreateSeries("B相摩擦", chart, dcdl.qxB);
                //C相
                if (dcdl.qxC != null && dcdl.qxC.Count > 0)
                    CreateSeries("C相摩擦", chart, dcdl.qxC);
            }
            else if (cTYPE == DCDZCurveTYPE.道岔动作功率曲线)
            {
                CreateSeries("功率", chart, dcdl.glqx);
            }
        }
        
        /// <summary>
        /// 生成标准曲线
        /// </summary>
        private void CreateBZSeries(ChartControl chart, bool isLeft)
        {
            //chart.Series.Clear();
            ObjDcdlType dcdl;
            if (isLeft)
                dcdl = now_dcdl_bz_left;
            else
                dcdl = now_dcdl_bz_right;

            if (cTYPE == DCDZCurveTYPE.道岔动作电流曲线)
            {
                //A相
                CreateSeries("A相标准", chart, dcdl.qxA); ;
                //B相
                if (dcdl.qxB != null && dcdl.qxB.Count > 0)
                    CreateSeries("B相标准", chart, dcdl.qxB);
                //C相
                if (dcdl.qxC != null && dcdl.qxC.Count > 0)
                    CreateSeries("C相标准", chart, dcdl.qxC);
            }
            else if (cTYPE == DCDZCurveTYPE.道岔动作功率曲线)
            {
                CreateSeries("功率", chart, dcdl.glqx);
            }
        }

        /// <summary>
        /// 查询设备曲线对应时间列表
        /// </summary>
        /// <param name="strDev">设备</param>
        private void CreateTimeListForDev(string strDev)
        {
            dcqx.Read_DcdlqxTimeList((string)this.cBoxCurveName.EditValue);

            while (!dcqx.Ready_DcdlqxTime)
            {
                if (dcqx.dlqxErrorFlag != 0)
                {
                    MessageBox.Show("查询不到对应时间列表");
                    return;
                }

                Thread.Sleep(20);
            }

            repositoryItemComboBox3.Items.Clear();

            foreach (DateTime dt in dcqx.DcdlqxTimeList)
            {
                ComboBoxItem item = new ComboBoxItem();
                
                repositoryItemComboBox3.Items.Add(dt.ToString("s", cu));
            }

            if (repositoryItemComboBox3.Items.Count > 0)
                this.cBoxCurveTime.EditValue = repositoryItemComboBox3.Items[0];
            
        }

        /// <summary>
        /// 查询曲线详细信息
        /// </summary>
        /// <param name="time"></param>
        /// <param name="DevName"></param>
        /// <param name="chart"></param>
        /// <param name="isHasMC"></param>
        /// <param name="isHasBZ"></param>
        /// <param name="isLeft"></param>
        private void CreateSeriesPoint(DateTime time, string DevName, ChartControl chart, bool isHasMC, bool isHasBZ, bool isLeft)
        {
            //查询电流、功率曲线
            dcqx.Read_DcdlqxValueList(time, DevName);

            while (!dcqx.Ready_DcdlqxValue)
            {
                if (dcqx.dlqxErrorFlag != 0)
                {
                    MessageBox.Show("查询不到对应电流曲线");
                    return;
                }

                Thread.Sleep(20);
            }
            ObjDcdlType dcdl = dcqx.DcdlqxValueList[DateTime.Parse((string)this.cBoxCurveTime.EditValue)];

            if (isLeft)
                now_dcdl_left = dcdl;
            else
                now_dcdl_right = dcdl;

            //查询摩擦曲线
            dcqx.Read_DcMCValueList(DevName);

            while (!dcqx.Ready_DcdzMcValue)
            {
                if (dcqx.mcqxErrorFlag != 0)
                {
                    //MessageBox.Show("查询不到对应电流摩擦曲线");
                    //return;
                    break;
                }

                Thread.Sleep(20);
            }

            foreach (ObjDcdlType mcValues in dcqx.DcdzMcqxValueList)
            {
                if (mcValues.zh_order == dcdl.zh_order)
                {
                    if (isLeft)
                        now_dcdl_mc_left = dcdl;
                    else
                        now_dcdl_mc_right = dcdl;
                    break;
                }
            }

            //查询标准曲线
            dcqx.Read_DcCkValueList(DevName);

            while (!dcqx.Ready_DcdzCKValue)
            {
                if (dcqx.ckqxErrorFlag != 0)
                {
                    //MessageBox.Show("查询不到对应电流标准曲线");
                    //return;
                    break;
                }

                Thread.Sleep(20);
            }

            foreach (ObjDcdlType ckValues in dcqx.DcdzCKqxValueList)
            {
                if (ckValues.zh_order == dcdl.zh_order)
                {
                    if (isLeft)
                        now_dcdl_bz_left = dcdl;
                    else
                        now_dcdl_bz_right = dcdl;
                    break;
                }
            }
        }
        

        /// <summary>
        /// 给一条曲线添加一组点
        /// </summary>
        /// <param name="series"></param>
        /// <param name="pointsToUpdate"></param>
        private void AddPoints(Series series, List<SeriesPoint> pointsToUpdate)
        {
            series.Points.AddRange(pointsToUpdate.ToArray());
        }

        /// <summary>
        /// 添加一条曲线
        /// </summary>
        /// <param name="seriesName"></param>
        /// <param name="chart"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        private void CreateSeries(string seriesName, ChartControl chart, List<ObjRCurValue> values)
        {
            //初始化Series
            Series series = new Series();
            //series.ArgumentScaleType = ScaleType.DateTime;
            series.CheckableInLegend = true;
            series.ValueScaleType = ScaleType.Numerical;
            series.Label.Border.Visible = false;
            series.Label.BackColor = Color.Transparent;
            series.ChangeView(ViewType.Line);
            series.LegendText = seriesName;

            chart.Series.Add(series);

            List<SeriesPoint> points = new List<SeriesPoint>();
            int index = 0;

            foreach (ObjRCurValue qxA in values)
            {
                index++;
                SeriesPoint point = new SeriesPoint(index, qxA.tValue.Value);
                points.Add(point);
            }
            AddPoints(series, points);
        }

        /// <summary>
        /// 是否表示摩擦曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckMC_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //CreateMCSeries(chart_left, true);
            //CreateMCSeries(chart_right, false);
            if (checkMC.Checked)
                isHasMC = true;
            else
                isHasMC = false;

            if ((e.Item as BarCheckItem).Checked)
            {
                bool flag = FindSeries("摩擦", true, true);
                if (!flag)
                    CreateMCSeries(chart_left, true);

                flag = FindSeries("摩擦", true, false);
                if (!flag)
                    CreateMCSeries(chart_right, false);
            }
            else
            {
                FindSeries("摩擦", false, true);
                FindSeries("摩擦", false, false);
            }
        }

        /// <summary>
        /// 是否表示标准曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckStand_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            //CreateBZSeries(chart_left, true);
            //CreateBZSeries(chart_right, false);
            if (checkStand.Checked)
                isHasBZ = true;
            else
                isHasBZ = false;
            if ((e.Item as BarCheckItem).Checked)
            {
                bool flag = FindSeries("标准", true, true);
                if (!flag)
                    CreateBZSeries(chart_left, true);

                flag = FindSeries("标准", true, false);
                if (!flag)
                    CreateBZSeries(chart_right, false);
            }
            else
            {
                FindSeries("标准", false, true);
                FindSeries("标准", false, false);
            }
        }

        /// <summary>
        /// 查找并显示对应曲线
        /// </summary>
        /// <param name="strKey"></param>
        /// <param name="isVisible"></param>
        /// <returns></returns>
        private bool FindSeries(string strKey, bool isVisible, bool isLeft)
        {
            ChartControl chart;
            if (isLeft)
                chart = chart_left;
            else
                chart = chart_right;

            List<Series> findSeriesList = new List<Series>();
            int findCount = 0;
            foreach (Series s in chart.Series)
            {
                if (s.LegendText.Contains(strKey))
                {
                    //s.Visible = isVisible;

                    findSeriesList.Add(s);
                    findCount++;
                }
            }

            if (!isVisible)
                foreach (Series s in findSeriesList)
                {
                    chart.Series.Remove(s);
                }
            else
                return false;

            if (findCount == 0)
                return false;
            else
                return true;
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnPrint_ItemClick(object sender, ItemClickEventArgs e)
        {
            chart_left.ShowPrintPreview();
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExport_ItemClick(object sender, ItemClickEventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "位图(*.bmp)|*.bmp";
            sf.FileName = "道岔动作电流曲线";
            if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                chart_left.ExportToImage(sf.FileName, ImageFormat.Bmp);
            }
        }

        /// <summary>
        /// 保存标准曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSaveStand_ItemClick(object sender, ItemClickEventArgs e)
        {
            dcqx.InsertDcCkMcQxTable(1, now_dcdl_left);
        }

        /// <summary>
        /// 保存摩擦曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSaveMC_ItemClick(object sender, ItemClickEventArgs e)
        {
            dcqx.InsertDcCkMcQxTable(2, now_dcdl_left);
        }

        private void chart_left_CustomDrawAxisLabel(object sender, CustomDrawAxisLabelEventArgs e)
        {
            AxisBase axis = e.Item.Axis;
            if (axis is AxisY || axis is AxisY3D || axis is RadarAxisY)
            {
                //double axisValue = (double)e.Item.AxisValue;
                e.Item.Text = e.Item.Text + "A";
            }
        }

        private void chart_right_CustomDrawAxisLabel(object sender, CustomDrawAxisLabelEventArgs e)
        {
            AxisBase axis = e.Item.Axis;
            if (axis is AxisY || axis is AxisY3D || axis is RadarAxisY)
            {
                //double axisValue = (double)e.Item.AxisValue;
                e.Item.Text = e.Item.Text + "A";
            }
        }

        private void chart_left_CustomDrawCrosshair(object sender, CustomDrawCrosshairEventArgs e)
        {
           
        }


    }
}